package com.papper.mng.dialect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.papper.common.bean.sys.SysCode;
import com.papper.common.bean.sys.SysUser;
import com.papper.common.constant.SystemConstants;
import com.papper.common.enums.LimitTypeEnum;
import com.papper.common.service.sys.SysCodeService;
import com.papper.common.service.sys.SysLimitService;
import com.papper.common.utils.PapperSpringUtil;
import com.papper.common.utils.tool.DateTool;
import com.papper.common.utils.tool.OrderTool;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.WebContext;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.util.StringUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @Author:Lajiao
 * @Date:2014年8月21日
 * @Time:下午12:30:20
 * @Description:自定义模板标签类
 */
@Service(value = "lj")
public class LjDialect {

	/**
	 * Code object.
	 *
	 * @param key   the key
	 * @param value the value
	 * @return the object
	 */
	public static Object code(String key, Object value) {
		SysCodeService s       = (SysCodeService) PapperSpringUtil.getBean("sysCodeService");
		SysCode        sysCode = s.findByKey(key);
		if (sysCode == null) {
			return value;
		}
		sysCode = s.findByKey(String.valueOf(value), sysCode.getId());
		if (sysCode == null) {
			return value;
		}
		if (StringUtil.isEmpty(sysCode.getCodeValue())) {
			return value;
		}
		return sysCode.getCodeValue();
	}

	/**
	 * Code style object.
	 *
	 * @param key   the key
	 * @param value the value
	 * @return the object
	 */
	public static Object codeStyle(String key, Object value) {
		SysCodeService s       = (SysCodeService) PapperSpringUtil.getBean("sysCodeService");
		SysCode        sysCode = s.findByKey(key);
		if (sysCode == null) {
			return value;
		}
		sysCode = s.findByKey(String.valueOf(value), sysCode.getId());
		if (sysCode == null) {
			return value;
		}
		if (StringUtil.isEmpty(sysCode.getCodeValue())) {
			return value;
		}
		if (sysCode.getCodeDesc().startsWith("c:")) {
			return "<selction style=\"color:" + sysCode.getCodeDesc().replaceAll("c:", "") + "\">" + sysCode.getCodeValue() + "</selction>";
		} else if (sysCode.getCodeDesc().startsWith("<span")) {
			return sysCode.getCodeDesc();
		} else {
			return sysCode.getCodeValue();
		}
	}

	/**
	 * Group list.
	 *
	 * @param key the key
	 * @return the list
	 */
	public static List group(String key) {
		SysCodeService s       = (SysCodeService) PapperSpringUtil.getBean("sysCodeService");
		SysCode        sysCode = s.findByKey(key);
		if (sysCode == null) {
			return null;
		}
		List<SysCode> list = s.findByParentId(sysCode.getId());
		return list;
	}

	/**
	 * Json key string.
	 *
	 * @param json the json
	 * @param key  the key
	 * @return the string
	 */
	public static String jsonKey(String json, String key) {
		try {
			JSONObject jsonObject = JSON.parseObject(json);
			return StringTool.nullToEmpty(jsonObject.getString(key));
		} catch (Exception ex) {
			return StringTool.EMPTY;
		}
	}

	/**
	 * Json key def string.
	 *
	 * @param json the json
	 * @param key  the key
	 * @param def  the def
	 * @return the string
	 */
	public static String jsonKeyDef(String json, String key, String def) {
		try {
			JSONObject jsonObject = JSON.parseObject(json);
			String     rtn        = jsonObject.getString(key);
			if (StringUtil.isEmpty(rtn)) {
				return def;
			}
			return rtn;
		} catch (Exception ex) {
			return def;
		}
	}

	/**
	 * Limit integer.
	 *
	 * @param limitKey the limit key
	 * @return the integer
	 */
	public static Integer limit(String limitKey) {
		SysUser sessionUser = (SysUser) WebContext.getServletRequest().getSession().getAttribute(SystemConstants.SESSION.SESSION_ADMIN_LOGIN);
		// 超级管理员
		if (sessionUser.getId() == 0) {
			return 1;
		}
		// 用户权限信息
		SysLimitService sysLimitService = (SysLimitService) PapperSpringUtil.getBean("sysLimitService");
		if (LimitTypeEnum.GROUP.getCode().equals(sessionUser.getLimitType())) {
			return sysLimitService.limit(sessionUser.getLimitType(), sessionUser.getGroupId().longValue(), limitKey);
		} else {
			return sysLimitService.limit(sessionUser.getLimitType(), sessionUser.getId(), limitKey);
		}
	}


	/**
	 * Contains integer.
	 *
	 * @param values the values
	 * @param value  the value
	 * @return the integer
	 */
	public static Integer contains(String values, String value) {
		if (StringUtil.isEmpty(value)) {
			return 0;
		}
		if (StringUtil.isEmpty(values)) {
			return 0;
		}
		List<String> valueList = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(values);
		if (valueList.contains(value)) {
			return 1;
		} else {
			return 0;
		}
	}

	/**
	 * Task code string.
	 *
	 * @param key   the key
	 * @param value the value
	 * @return the string
	 */
	public static String taskCode(String key, String value) {
		String              shopCode    = value.substring(0, value.indexOf("_"));
		String              vipCode     = value.substring(value.indexOf("_") + 1);
		Map<String, String> taskContent = Maps.newHashMap();
		taskContent.put("shopCode", shopCode);
		taskContent.put("vipCode", vipCode);
		return taskContent.get(key);
	}

	/**
	 * Encode uri string.
	 *
	 * @param url the url
	 * @return the string
	 */
	public static String encodeURI(String url) {
		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}

	/**
	 * 截取字符串,后面添加...
	 *
	 * @param name      the name
	 * @param maxLength the max length
	 * @return string string
	 */
	public static String cutStringAddStr(String name, Integer maxLength) {
		return StringTool.cutStringAddStr(name, maxLength);
	}

	/**
	 * 位数补零
	 *
	 * @param data   the data
	 * @param length the length
	 * @return string string
	 */
	public static String zerofill(String data, Integer length) {
		return OrderTool.zerofill(data, length);
	}

	/**
	 * Null to empty string.
	 *
	 * @param value the value
	 * @return the string
	 */
	public static String nullToEmpty(Object value) {
		return StringTool.nullToEmpty(value);
	}

	/**
	 * 百分比
	 *
	 * @param dividend the dividend
	 * @param divisor  the divisor
	 * @return string string
	 */
	public static String percent(Object dividend, Object divisor) {
		return StringTool.percent(dividend, divisor);
	}

	/**
	 * 价格格式化
	 *
	 * @param dividend the dividend
	 * @return string string
	 */
	public static String price(Object dividend) {
		return StringTool.price(dividend);
	}

	/**
	 * Price append string.
	 *
	 * @param value  the value
	 * @param append the append
	 * @return the string
	 */
	public static String priceAppend(Object value, String append) {
		if (value == null) {
			return append;
		}
		Double d = StringTool.parseDouble(value.toString(), null);
		if (d == null || d == 0) {
			return append;
		}
		return "<selction style=\"color:red;\">¥ " + StringTool.price(d) + "</selction>";
	}


	/**
	 * Date object.
	 *
	 * @param date the date
	 * @return the object
	 */
	public static Object date(Object date) {
		if (date instanceof String) {
			return date;
		}
		if (date instanceof Date) {
			return DateTool.formatDate((Date) date, DateTool.FULL_TRADITION_PATTERN);
		}
		if (date instanceof Long) {
			return DateTool.formatDate(new Date((Long) date), DateTool.FULL_TRADITION_PATTERN);
		}

		return date;
	}

	/**
	 * Date fmt object.
	 *
	 * @param date   the date
	 * @param format the format
	 * @return the object
	 */
	public static Object dateFmt(Object date, String format) {
		if (date instanceof String) {
			return date;
		}
		if (date instanceof Date) {
			return DateTool.formatDate((Date) date, format);
		}
		if (date instanceof Long) {
			return DateTool.formatDate(new Date((Long) date), format);
		}

		return date;
	}

	/**
	 * Indistinct string.
	 *
	 * @param value the value
	 * @param left  the left
	 * @param right the right
	 * @return the string
	 */
	public static String indistinct(String value, Integer left, Integer right) {
		if (StringUtil.isEmpty(value)) {
			return value;
		}
		int length = value.length();
		if (length > left) {
			value = m(left) + value.substring(left, value.length());
		} else {
			return m(left);
		}

		if (length > right) {
			value = value.substring(0, length - right) + m(right);
		} else {
			return m(right);
		}

		return value;
	}

	/**
	 * Indistinct 2 string.
	 *
	 * @param value the value
	 * @param left  the left
	 * @param right the right
	 * @return the string
	 */
	public static String indistinct2(String value, Integer left, Integer right) {
		if (StringUtil.isEmpty(value)) {
			return value;
		}
		String rtn    = "";
		int    length = value.length();
		if (length > left) {
			rtn = rtn + value.substring(0, left);
		}
		rtn = rtn + "****";
		if (length > right) {
			rtn = rtn + value.substring(length - right, length);
		}
		return rtn;
	}


	private static String m(int length) {
		StringBuffer rtn = new StringBuffer();
		for (int i = 0; i < length; i++) {
			rtn.append("*");
		}
		return rtn.toString();
	}
}
